//
//  RoomViewController.m
//  MooreDoll
//
//  Created by Joe on 2014/12/4.
//  Copyright (c) 2014年 Tank. All rights reserved.
//
#import "ClockViewController.h"

#import "RoomViewController.h"
#include "libxclient.h"
#include "lame.h"
#import "ChatSettingTableViewController.h"
//#import "Chat.h"

@interface RoomViewController ()

@end

@implementation RoomViewController
@synthesize Array_Msg,chatRoom,Array_memberImage,Vw_Buttons;
//@synthesize room;



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateChatRoomMessage) name:@"updateMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:@"UIKeyboardWillShowNotification"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgress:) name:@"sendFileProgress" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgress:) name:@"receiveFileProgress" object:nil];
   
    
    
    //取消tableView的區間線條
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    managedObjectContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
    
    //取得所有使用者頭像
    #warning Patrick 暫時只取1人，等Will回覆Group issue
    NSFetchRequest *rosterFetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *rosterEntity = [NSEntityDescription entityForName:@"Roster" inManagedObjectContext:managedObjectContext];
    
    NSString *prdicateString = [[NSString alloc] initWithFormat:@"jid == '%@'",chatRoom.owner];
    NSPredicate *rosterPredicate = [NSPredicate predicateWithFormat:prdicateString];
    [rosterFetch setEntity:rosterEntity];
    [rosterFetch setPredicate:rosterPredicate];
    Roster *roomMate = [managedObjectContext executeFetchRequest:rosterFetch error:nil].firstObject;
    
    // fetch JID
    NSString *userJID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"];
    NSString *userImagePath = [[NSUserDefaults standardUserDefaults] objectForKey:@"userImage"];
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] objectForKey:@"NICKNAME"];

    
    // set Image
    UIImage *userImg = nil,*roomMateImg = nil;
    NSData *userImgData     = [[NSFileManager defaultManager] contentsAtPath:userImagePath],
    *roomMateImgData = [[NSFileManager defaultManager] contentsAtPath:roomMate.photoPath];
    
    if (userImgData != nil)
        userImg = [UIImage imageWithData:userImgData];
    if (roomMateImgData != nil)
        roomMateImg = [UIImage imageWithData:roomMateImgData];
    
    NSDictionary *dic         = userImg ?
    @{@"jid":userJID,@"image":userImg    , @"nickName":userNickName}:
    @{@"jid":userJID,@"image":@"nothing" , @"nickName":userNickName};
    
    NSDictionary *roomMateDic = roomMateImg ?
    @{@"jid":roomMate.jid,@"image":roomMateImg , @"nickName":roomMate.nickeName}:
    @{@"jid":roomMate.jid,@"image":@"nothing"  , @"nickName":roomMate.nickeName};
    
    Array_memberImage = [[NSMutableArray alloc] initWithObjects:dic,roomMateDic, nil];
    
    
    
    //取得該聊天室所有資料
    
    [self updateChatRoomMessage];
    
    if ([chatRoom.owner rangeOfString:@"toy"].location != NSNotFound)
    {
        Vw_Buttons = [[[NSBundle mainBundle] loadNibNamed:@"RoomButtomsMooreDoll"
                                                    owner:self
                                                  options:nil]
                      objectAtIndex:0];
        isDollRoom = YES;
    }
    else
    {
        Vw_Buttons = [[[NSBundle mainBundle] loadNibNamed:@"RoomButtomsFriend"
                                                    owner:self
                                                  options:nil]
                      objectAtIndex:0];
        isDollRoom = NO;
    }
    [Vw_Buttons setFrame:CGRectMake(0,
                                    self.view.frame.size.height- Vw_Buttons.frame.size.height,
                                    Vw_Buttons.frame.size.width,
                                    Vw_Buttons.frame.size.height)];
    [self.view addSubview:Vw_Buttons];
    Vw_Buttons.delegate = self;
    Vw_Buttons.TF_Bmessage.delegate = self;
    
}

//Tank{
- (IBAction)SettingButtonEvent:(id)sender
{
    if ([chatRoom.owner rangeOfString:@"toy"].location != NSNotFound)
    {
        ChatSettingTableViewController *ChatSettingVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ChatSettingTableViewController"];
        
        ChatSettingVC.getJid = chatRoom.owner;
        
        [self.navigationController pushViewController:ChatSettingVC
                                             animated:YES];
    }
}
//}


#pragma mark Button Event

-(void)doButtonEventWithIdentify:(NSString *)identify
{
    if ([identify isEqualToString:@"Record"])
        [self recordButtonPress];
    
    if ([identify isEqualToString:@"Music"])
        [self musicButtonPress];
    
    if ([identify isEqualToString:@"Clock"])
        [self clockSettingButtonPress];
    
    if ([identify isEqualToString:@"Cloud"])
        [self cloudServiceButtonPress];
    
    if ([identify isEqualToString:@"MessageSend"])
        [self sendMessageButtonPress];
    
}

-(void)recordButtonPress
{
    //放透明view讓使用者無法觸碰其他元件
    [self showMaskViewWithNotificatio:nil];
    
    //新增micView ＋滑出動畫
    if (Vw_mic == nil)
    {
        Vw_mic = [[[NSBundle mainBundle] loadNibNamed:@"MicView"
                                                owner:self
                                              options:nil] objectAtIndex:0];
        [Vw_mic microphoneSetting];
        Vw_mic.delegate = self;
        [Vw_mic setFrame:CGRectMake(0,
                                   self.view.frame.size.height,
                                   Vw_mic.frame.size.width,
                                   Vw_mic.frame.size.height)];
        [self.view addSubview:Vw_mic];
        [UIView animateWithDuration:0.5 animations:
         ^{
            [Vw_mic setFrame:CGRectMake(0,
                                        self.view.frame.size.height-Vw_mic.frame.size.height,
                                        Vw_mic.frame.size.width,
                                        Vw_mic.frame.size.height)];
            
        }];
    }
}

-(void)musicButtonPress
{
    SongListViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SongListViewController"];
    svc.chatRoom = chatRoom;
    svc.delegate = self;
    [self.navigationController pushViewController:svc
                                         animated:YES];
}

-(void)clockSettingButtonPress
{
    ClockViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"ClockViewController"];
    [self.navigationController pushViewController:svc
                                         animated:YES];
}

-(void)cloudServiceButtonPress
{
    // do cloud service
}

-(void)sendMessageButtonPress
{
    // send msg
    NSString *message = Vw_Buttons.TF_Bmessage.text;
    
    if ([message isEqualToString:@""] || message == nil)
        return;
    else
    {
        
    
        NSString *fromWhoJID    = [[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"];
        if ([fromWhoJID rangeOfString:@"@bbserver-virtualbox"].location ==NSNotFound)
        {
            fromWhoJID = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"] stringByAppendingString:@"@bbserver-virtualbox"];
        }
    
        NSString *sendMessage = [NSString stringWithFormat:@"chatMessage:%@",message];
        
        NSDictionary *dic = @{@"fromWho"    : fromWhoJID,
                              @"toWho"      : chatRoom.owner,
                              @"update"     : [NSDate date],
                              @"message"    : sendMessage,
                              @"audioPath"  : @"",
                              @"chatRoom"   : chatRoom};
        
        [[NetworkManager sharedInstance].sendArray addObject:dic];
        
        
        #warning Patrick : use custom formate to send chat message!
        /*
         send message formate : chatMessage:content
         */
        
        
        xclient_message_send((char *)[chatRoom.owner UTF8String], (char *)[sendMessage UTF8String]);
        
        [self removeMaskView];
    }
}


-(void)sendMusicWithMediaItem:(MPMediaItem *)item
{
    MPMediaItem *mediaItem = item;
    NSString *songTitle = [mediaItem valueForProperty: MPMediaItemPropertyTitle];
    AVURLAsset *sset = [AVURLAsset assetWithURL:[mediaItem valueForProperty:MPMediaItemPropertyAssetURL]];
    NSString *fileType = [[[[sset.URL absoluteString] componentsSeparatedByString:@"?"] objectAtIndex:0] pathExtension];
    
    //init export, here you must set "presentName" argument to "AVAssetExportPresetPassthrough". If not, you will can't export mp3 correct.
    AVAssetExportSession *export = [[AVAssetExportSession alloc] initWithAsset:sset presetName:AVAssetExportPresetPassthrough];
    
    NSLog(@"export.supportedFileTypes : %@",export.supportedFileTypes);
    //export to mov format.
    export.outputFileType = @"com.apple.quicktime-movie";
    
    export.shouldOptimizeForNetworkUse = YES;
    
    NSString *extension = (__bridge NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)export.outputFileType, kUTTagClassFilenameExtension);
    
    NSLog(@"extension %@",extension);
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.%@",songTitle,extension];
    
    NSURL *outputURL = [NSURL fileURLWithPath:path];
    export.outputURL = outputURL;
    [export exportAsynchronouslyWithCompletionHandler:
     ^{
         if (export.status == AVAssetExportSessionStatusCompleted)
         {
             //then rename mov format to the original format.
             NSFileManager *manage = [NSFileManager defaultManager];
             
             
             NSDate *date = [NSDate date];
             NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
             [dateFormatter setDateFormat:@"YY-MM-dd-e_HH_mm-ss"];
             NSString *fildName = [@"exported_" stringByAppendingString:[dateFormatter stringFromDate:date]];
             NSString *mp3Path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.%@",fildName,fileType];
             fildName = [fildName stringByAppendingFormat:@".%@",fileType];
             NSError *error = nil;
             NSString *pathInApp = [mp3Path substringFromIndex:[mp3Path rangeOfString:@"/Documents"].location];
             [manage moveItemAtPath:path toPath:mp3Path error:&error];
             
             
             //check mp3 file name, search ".m4a" or "caf" is exist or not
             // if file is "m4a" "caf" formate , convert to mp3
#warning Patrick : If music type is m4a or caf , must convert to mp3 (interrupt now, discus with Will)
             
             [self sendAudioToXMPPWithDataPath:mp3Path andFileName:fildName andPathInApp:pathInApp];
             
             NSLog(@"error %@",error);
             
         }
         else
         {
             NSLog(@"%@",export.error);
         }
         
     }];

}
-(void)sendAudioToXMPPWithDataPath:(NSString *)mp3Path andFileName:(NSString *)fileName andPathInApp:(NSString *)pathInApp
{
    
    NSString *name = fileName;
    name = [name substringToIndex:[name rangeOfString:@".mp3"].location];
    
    NSString *fromWhoJID    = [[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"];
    if ([fromWhoJID rangeOfString:@"@bbserver-virtualbox"].location == NSNotFound)
        fromWhoJID = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"] stringByAppendingString:@"@bbserver-virtualbox"];
    
    NSDictionary *dic = @{@"fromWho"    : fromWhoJID,
                          @"toWho"      : chatRoom.owner,
                          @"update"     : [NSDate date],
                          @"message"    : @"",
                          @"audioPath"  : pathInApp,
                          @"chatRoom"   : chatRoom,
                          @"mp3Path"    : mp3Path};
    
    [[NetworkManager sharedInstance].sendArray addObject:dic];
    
    //send mp3 file to xmpp
    xclient_ftp_send((char *)[mp3Path UTF8String],
                     (char *)[name UTF8String],
                     (char *)[chatRoom.owner UTF8String]);
    
    [self removeMaskView];
    
}



#pragma mark UIAnimtae Event

-(void)showMaskViewWithNotificatio:(NSNotification *)note
{
    CGRect rect ;
    if (note == nil)
    {
        //點擊錄音按鈕，定義maskView的位置大小
        rect = CGRectMake(0,
                          0,
                          self.view.frame.size.width,
                          self.view.frame.size.height);
    }
    else
    {
        //鍵盤升起時，定義maskView
        rect = CGRectMake(0,
                          0,
                          self.view.frame.size.width,
                          self.view.frame.size.height - Vw_Buttons.frame.size.height);
    }
    
    
    //放透明view讓使用者無法觸碰其他元件
    if (maskView == nil)
    {
        maskView = [[UIView alloc] initWithFrame: rect ];
        maskView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:maskView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(removeMaskView)];
        [maskView addGestureRecognizer:tap];
    }
}

-(void)removeMaskView
{
    //手指觸碰透明view，收鍵盤
    if (maskView)
    {
        [maskView removeFromSuperview];
        maskView = nil;
    }
    
    if (Vw_Buttons.TF_Bmessage.isFirstResponder)
        [Vw_Buttons.TF_Bmessage resignFirstResponder];
    
    
    [UIView animateWithDuration:0.1 animations:^
    {
         self.view.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);
         if (Vw_mic)
             [Vw_mic setFrame:CGRectMake(0,self.view.frame.size.height,Vw_mic.frame.size.width,Vw_mic.frame.size.height)];
    }
    completion:^(BOOL finished)
    {
        if (Vw_mic)
        {
            [Vw_mic removeFromSuperview];
            Vw_mic = nil;
        }
    }];
    
}

- (void) keyboardWillShow:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    [self showMaskViewWithNotificatio:note];
    
    [UIView animateWithDuration:0.4 animations:
     ^{
         //鍵盤出現時整個view上移
         self.view.frame = CGRectMake(0,
                                      -kbSize.height,
                                      self.view.frame.size.width,
                                      self.view.frame.size.height);

     }];
}




#pragma mark RoomMessage Update

-(void)updateChatRoomMessage
{
    //更新聊天室內容
    Array_Msg = nil;
    
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ChatMessage" inManagedObjectContext:managedObjectContext];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"content.owner == %@",chatRoom.owner];
    
    [fetch setEntity:entity];
    [fetch setPredicate:predicate];
    [fetch setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"update" ascending:YES]]];
    
    Array_Msg = [[NSMutableArray alloc] initWithArray:[managedObjectContext executeFetchRequest:fetch error:nil]];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        int rowNumbers = [self.tableView numberOfRowsInSection:0];
//        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rowNumbers-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    });

    
}



#pragma mark UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return Array_Msg.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   // RoomChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RoomChatCell"];
    if (indexPath.row == (Array_Msg.count)) {
        NSLog(@"top");
    }
    RoomChatCell *cell;
    if (cell == nil)
    {
        
        ChatMessage *message = [Array_Msg objectAtIndex:indexPath.row];
        NSString *userJID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userJID"];
        if ([userJID rangeOfString:@"@bbserver-virtualbox"].location == NSNotFound){
            userJID = [userJID stringByAppendingString:@"@bbserver-virtualbox"];
        }
        
        if ([message.fromWho isEqualToString:userJID])
        {
            //使用者自己的cell
            cell = [[[NSBundle mainBundle] loadNibNamed:@"RoomChatCellRight" owner:self options:nil] objectAtIndex:0];
            //cell.backgroundColor = [UIColor greenColor];
            
        }
        else
        {
            //好友的cell
            cell = [[[NSBundle mainBundle] loadNibNamed:@"RoomChatCellLeft" owner:self options:nil] objectAtIndex:0];
            //cell.backgroundColor = [UIColor whiteColor];
        }
        cell.delegate = self;
        
        
        [cell cellSettingWithChatMessage:message andImageArray:Array_memberImage];

    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    RoomChatCell *cellR = [[[NSBundle mainBundle] loadNibNamed:@"RoomChatCellRight" owner:self options:nil] objectAtIndex:0];
    RoomChatCell *cellL = [[[NSBundle mainBundle] loadNibNamed:@"RoomChatCellLeft" owner:self options:nil] objectAtIndex:0];
    
    if (cellR.frame.size.height > cellL.frame.size.height)
        return cellR.frame.size.height;
    else
        return cellL.frame.size.height;
}



-(void)cellsMusicPlayWithCell:(RoomChatCell *)cell
{
    NSArray *cellArray = [self.tableView visibleCells];
    
    [cell playMusic];
    
    for (RoomChatCell *cellObject in cellArray)
    {
        if (cellObject != cell && [cellObject isKindOfClass:[RoomChatCell class]])
            [cellObject stopMusic];
        
    }
    
}

-(void)updateProgress:(NSNotification *)notification
{
    NSArray         *cells          = [self.tableView visibleCells];
    NSDictionary    *progressInfo   = [notification object];
    NSString        *sid            = sid = [progressInfo objectForKey:@"sid"];
    
    for (UITableViewCell *cell in cells)
    {
        if ([cell isKindOfClass:[RoomChatCell class]])
        {
            RoomChatCell *roomChatCell = (RoomChatCell *)cell;
            if ([roomChatCell.sid isEqualToString:sid])
            {
                dispatch_async(dispatch_get_main_queue(),
                ^{
                    [roomChatCell progressValueChange:progressInfo];
                });
                break;
            }
        }
    }
    
}

@end
